<?php
/**
 * @version $Id: includer.php 24 2009-03-29 13:19:58Z der.el.kuku $
 * @package    WikiInclude
 * @subpackage
 * @author     EasyJoomla {@link http://www.easy-joomla.org Easy-Joomla.org}
 * @author     Nikolai Plath {@link http://www.easy-joomla.org}
 * @author     Created on 26-Mar-2009
 */

//--No direct access
defined( '_JEXEC' ) or die( '=;)' );

/**
 * WikiInclude
 *
 * Includes a page from Mediawiki using the following tchnique:
 * A Mediawiki Extension which includes a wikipage by a name given through a $_GET variable.
 * To avoid caching we use the Mediawiki command <pre>action=purge</pre>
 * We want only the text output, so we have to call the page once again with <pre>action=render</pre>
 *
 * @package    WikiInclude
 * @subpackage Models
 */
class WikiIncluder
{

	function getPage($name='', $id='', $url='http://wiki.joomla-nafu.de/jn/', $debug=false)
	{
		$DEBUG = true;

		$stdURL = 'http://wiki.joomla-nafu.de/jn/';
		$wikiPage = new JObject();
		$wikiPage->id = null;
		$wikiPage->title = '';
		$wikiPage->text = '';
		$wikiPage->revno = '??';

		$db = JFactory::getDBO();
		if( ! $id && ! $name )
		{
			$wikiPage->error = 'no id, no name...';

			return $wikiPage;
		}
		if( ! $name )
		{
			$query = ' SELECT title FROM #__wikiinclude '.
					'  WHERE id = '.intval($id);
			$db->setQuery( $query );
			$name = $db->loadResult();
			if( ! $name )
			{
				$wikiPage->error = 'page not found in db (by id)';
					
				return $wikiPage;
			}

		}
		if( ! $id )
		{
			$query = ' SELECT id FROM #__wikiinclude '.
					'  WHERE title = '.$db->quote($name);
			$db->setQuery( $query );
			$id = $db->loadResult();
			if( ! $id )
			{
				$wikiPage->error = 'page not found in db (by name)';
					
				return $wikiPage;
			}
		}

		echo( $DEBUG ) ? 'getting: '.$name.'<br />' : '';
		$url = $stdURL.$name;
		//		$result = self::getWebPage( $url.'&action=purge', true );
		//		if ( $result['errno'] != 0 )
		//		{
		//			$wikiPage->error = 'error: bad url, timeout, redirect loop ... '.$result['errno'];
		//		}
		//		else if ( $result['http_code'] != 200 )
		//		{
		//			$wikiPage->error = 'error: no page, no permissions, no service ... '.$result['http_code'];
		//		}
		//		else
		//		{
		$result = self::getWebPage( $url.'?action=render' );
		if ( $result['errno'] != 0 )
		{
			$wikiPage->error = 'error: bad url, timeout, redirect loop ... '.$result['errno'];
		}
		else if ( $result['http_code'] != 200 )
		{
			$wikiPage->error = 'error: no page, no permissions, no service ... '.$result['http_code'];
		}
		else
		{
			$wikiPage->id = $id;
			$wikiPage->title = $name;
			/**** work here... ****/
			$cleaned = $result['content'];
			$cleaned = str_replace('http://wiki.joomla-nafu.de/index.php?title=', 'index.php?option=com_content&task=findkey&tmpl=component&keyref=', $cleaned);
			$cleaned = str_replace('http://wiki.joomla-nafu.de/jn/', 'index.php?option=com_content&task=findkey&tmpl=component&keyref=', $cleaned);

			$cleaned = str_replace('&action=edit&redlink=1', '', $cleaned);
			#http://wiki.joomla-nafu.de/index.php?title=Screen.content.15&action=edit&redlink=1
			#http://xhelp.der-beta-server.de/index.php?option=com_content&task=findkey&tmpl=component&keyref=screen.cpanel.15
			#http://test.nik/j_159_de/index.php?option=com_content&task=findkey&tmpl=component&keyref=Screen.content.15&action=edit&redlink=1&Itemid=54
			#http://wiki.joomla-nafu.de/jn/Screen.users.15

			//-- Remove HS_refs
			#<div style="background-color: #ffe5b2
			$regex = "%<div style=\"background-color: #ffe5b2(.*?)\</div>%";
			preg_match_all( $regex, $cleaned, $matches );
			if( count($matches[0]))
			{
				foreach ($matches[0] as $match) {
					$cleaned = str_replace($match, '', $cleaned);
				}
			}
echo( $DEBUG ) ? 'cleared '.count($matches[0]).' HS_refs<br />' : '';

			//-- Remove comments
			#<!-- .... -->
			$regex = "%<!--(.*?)-->%s";
			preg_match_all( $regex, $cleaned, $matches );
			if( count($matches[0]))
			{
				foreach ($matches[0] as $match) {
					$cleaned = str_replace($match, '', $cleaned);
				}
			}
echo( $DEBUG ) ? 'cleared '.count($matches[0]).' comments<br />' : '';
			
			//-- Remove docs_refs
			#<table style="border:1px solid #8888aa; background-color:#f7f8ff;
			$regex = "%<table style=\"border:1px solid #8888aa; background-color:#f7f8ff;(.*?)\</table>%s";
			preg_match_all( $regex, $cleaned, $matches );
			if( count($matches[0]))
			{
				foreach ($matches[0] as $match) {
					$cleaned = str_replace($match, '', $cleaned);
				}
			}
echo( $DEBUG ) ? 'cleared '.count($matches[0]).' docs_refs<br />' : '';
			#			print_r($matches);

			$wikiPage->text = $cleaned;

			/*
			 * Find revision number
			 */
			$regex = "/Revno.:\[(.*?)\]/";

			preg_match_all( $regex, $cleaned, $matches );
			if( isset($matches[1][0]))
			{
				$wikiPage->revno = self::convertTimeStamp($matches[1][0]);
			}
		}
		//		}
		return $wikiPage;
	}//function

	/**
	 * Converts a Mediawiki timestamp to MySQL format
	 *
	 * @param string $str
	 * @return string
	 */
	function convertTimeStamp($str)
	{
		if(strlen($str) != 14 )
		{
			//invalid timestamp
			return('invalid timestamp');
		}
		#		2009-03-26 18:13:47
		#		0123 45 67 89 01 23
		$y = substr($str, 0, 4);
		$m = substr($str, 4, 2);
		$d = substr($str, 6, 2);
		$h = substr($str, 8, 2);
		$mi = substr($str, 10, 2);
		$s = substr($str, 12, 2);
		return("$y-$m-$d $h:$mi:$s");
	}



	/**
	 * Get a web file (HTML, XHTML, XML, image, etc.) from a URL.  Return an
	 * array containing the HTTP server response header fields and content.
	 */
	function getWebPage( $url, $purge=false )
	{
		$options = array(
		CURLOPT_RETURNTRANSFER => true,     // return web page
		CURLOPT_HEADER         => false,    // don't return headers
		#	CURLOPT_FOLLOWLOCATION => true,     // follow redirects
		CURLOPT_ENCODING       => "",       // handle all encodings
		CURLOPT_USERAGENT      => "kukuspider", // who am i
		CURLOPT_AUTOREFERER    => true,     // set referer on redirect
		CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
		CURLOPT_TIMEOUT        => 120,      // timeout on response
		CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
		);

		if($purge)
		{
			$options[CURLOPT_POST] = true;
			$options[CURLOPT_POSTFIELDS] = 'submit=OK';
		}

		$ch      = curl_init( $url );
		curl_setopt_array( $ch, $options );
		$content = curl_exec( $ch );
		$err     = curl_errno( $ch );
		$errmsg  = curl_error( $ch );
		$header  = curl_getinfo( $ch );
		curl_close( $ch );

		$header['errno']   = $err;
		$header['errmsg']  = $errmsg;
		$header['content'] = $content;
		return $header;
	}//function

}//class
